<template>
  <Layout dis-hover>
    <div :style="{width: '100%',height: divHeight, }"><!--border: '1px solid #dcdee2'-->
      <Split v-model="split1">
        <div slot="left" class="demo-split-pane">
          <Tree :data="treeData" :render="renderContent" :load-data="handleLoadData" ref="tree" expand-node></Tree>
          <Dropdown trigger="click" style="margin-left:20px" placement="right-start"
                    ref="contentMenu" @on-click="selectTreeItem">
            <DropdownMenu slot="list"
                          v-if="this.user.loginId === this.Common.admin || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined">
              <DropdownItem name="addPoint" v-if="showPoint1">新增</dropdownitem>
              <DropdownItem name="editPoint" v-if="showPoint">修改</dropdownitem>
              <DropdownItem name="deletePoint" v-if="showPoint2">删除</dropdownitem>
            </dropdownmenu>
          </dropdown>
        </div>
        <div slot="right" class="demo-split-pane">
          <Form :label-width="90" ref="formInline" :model="formInline">
            <Row :gutter="16" class="query-form" style="margin-left: 10px">
              <i-col span="8">
                <FormItem label="资料名称：">
                  <Input v-model="formInline.name" placeholder="请输入资料名称"/>
                </FormItem>
              </i-col>
              <i-col span="16">
                <div style="float: right">
                  <Button class="ivu-btn-reset" @click="cancel">重置</Button>
                  <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
                </div>
              </i-col>
            </Row>
          </Form>
          <Row type="flex" justify="start" v-show="!addButten" class="query-form" style="margin-left: 10px">
            <i-col>
              <Button
                  v-if="this.user.loginId === this.Common.admin || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined"
                  class="ivu-btn-add" icon="md-add" @click="add">新增
              </Button>
            </i-col>
          </Row>
          <Table ref='table' style="margin-top: 10px;margin-left: 10px" :loading="loading" border :columns="Columns"
                 :data="infos" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
          <Row type="flex" justify="end" style="margin-top: 10px">
            <i-col>
              <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                    @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray"
                    show-total show-sizer show-elevator/>
            </i-col>
          </Row>
        </div>
      </Split>
      <Modal v-model="modal1" title="文件信息" width="600" :mask-closable="false">
        <Form ref="formCustom1" :model="form1data" :rules="ruleCustom" label-position="top"
              enctype="multipart/form-data">
          <Row>
            <i-col>
              <FormItem label="名称：" prop="name">
                <Input v-model="form1data.name" placeholder="请输入资料名称"/>
              </FormItem>
            </i-col>
          </Row>
          <!-- <Row>
               <i-col>
                   <FormItem label="封面图片：" prop="fileFm">
                       <div class="upload-list" v-for="(item, index) in uploadList" :key="index">
                           <img :src="item.picture" style="margin-right: 20px">
                           <div class="upload-list-cover">
                               <Icon type="ios-trash-outline" @click.native="handleRemove(item, 'picture')"></Icon>
                           </div>
                       </div>
                       <Upload v-if="!uploadList.length!=0"
                               name="files"
                               :before-upload="handleUpload"
                               ref="imgUpload"
                               :format="['jpg','jpeg','png','gif']"
                               :max-size="2048"
                               :action="uploadImgUrl"
                               type="drag"
                               style="display: inline-block;width:58px;">
                           <div style="width: 58px;height:58px;line-height: 58px;">
                               <Icon type="ios-camera" size="20"></Icon>
                           </div>
                       </Upload>
                       <div v-if="imgFile !== null">{{ imgFile.name }}</div>
                   </FormItem>
               </i-col>
           </Row>-->
          <Row>
            <i-col>
              <FormItem label="附件上传：">
                <Upload
                    :show-upload-list="false"
                    name="files"
                    ref="docUpload"
                    :before-upload="handleUpload2"
                    type="drag"
                    :action="fileUrl"
                >
                  <div style="padding: 20px 0">
                    <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                    <p>请选择附件</p>
                    <!--<span style="font-size:8px;color: #797a64">支持扩展名：.pdf .doc .docx</span>-->
                  </div>
                </Upload>
                <div>{{ docName }}</div>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col>
              <FormItem label="排序：">
                <Input type="textarea" v-model="form1data.content" placeholder="请输入文件顺序" maxlength="2000"/>
              </FormItem>
            </i-col>
          </Row>
        </Form>
        <div slot="footer">
          <Button class='ivu-btn-save' @click="saveInfo">保存</Button>
          <Button class='ivu-btn-cancel' @click="closeModal">取消</Button>
        </div>
      </Modal>


      <Modal v-model="isShow" :title="selectNodeInfo.title+(isUpdate?'修改':'新增')" width="600" :mask-closable="false"
             @on-cancel="isShow=false;formItem={}">
        <div style="margin: 0 20px" v-if="isShow">
          <Form :model="formItem" ref="formCustom" :rules="ruleCustom">
            <Row>
              <i-col>
                <FormItem label="分类名称" prop="name">
                  <Input type="text" v-model="formItem.name" placeholder="请输入分类名称"></Input>
                </FormItem>
              </i-col>
            </Row>
            <Row>
              <i-col>
                <FormItem label="排序" prop="seq">
                  <Input type="text" v-model="formItem.seq" placeholder="请输入排序"></Input>
                </FormItem>
              </i-col>
            </Row>
          </Form>
        </div>
        <div slot="footer">
          <Button class='ivu-btn-save' v-if="showEdit" @click="save">确定</Button>
          <Button class='ivu-btn-cancel' @click="isShow=false;formItem={}">取消</Button>
        </div>
      </Modal>

    </div>
  </Layout>
</template>

<script>

import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';

export default {
  name: "materialsTree",
  data() {
    return {
      docName: '',
      user: sessionStorage('userId').getObject('userId'),
      uploadList: [],
      fileUrl: '',
      uploadImgUrl: '',
      materialsId: '',
      categoryId: '',
      isUpdate: false,
      imgFile: null,
      docFile: null,
      tableHeight: '',
      divHeight: '',
      loading: false,
      split1: 0.25,
      treeData: [/*{
                    id : '-1',
                    name : '文件夹',
                    title: '文件夹',
                    parentId:'-1',
                    seq: 1,
                    children: []
                }*/],
      modal1: false,
      isShow: false,
      showEdit: false,
      formItem: {
        name: ''
      },
      selectNodeInfo: {title: ''},
      showPoint: false,
      showPoint1: true,
      showPoint2: false,
      formInline: {},
      form1data: {},
      Columns: [
        {
          type: 'index',
          title: '编号',
          width: 80,
          align: 'center',
        },
        {
          title: '资料名称',
          align: 'center',
          key: 'name',
          render: (h, params) => {
            return h('div', [
              h('span', params.row.name || '--')
            ]);
          }
        },
        {
          title: '创建时间',
          align: 'center',
          key: 'createDateStr',
          render: (h, params) => {
            return h('div', [
              h('span', params.row.createDateStr || '--')
            ]);
          }
        },
        {
          title: '操作',
          align: 'center',
          width: '160',
          key: 'updateDate',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {
                  fontSize: '14px',
                  color: this.user.loginId === this.Common.admin || this.user.userId === params.row.createUserId || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined ? '' : '#d0d0d0',
                  pointerEvents: this.user.loginId === this.Common.admin || this.user.userId === params.row.createUserId || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined ? '' : 'none'
                },
                on: {
                  click: () => {
                    this.update(params.row);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {
                  fontSize: '14px',
                  color: this.user.loginId === this.Common.admin || this.user.userId === params.row.createUserId || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined ? 'red' : '#d0d0d0',
                  pointerEvents: this.user.loginId === this.Common.admin || this.user.userId === params.row.createUserId || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined ? '' : 'none'
                },
                on: {
                  click: () => {
                    this.delete(params.row);
                  }
                }
              }, '删除'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {type: 'primary', size: 'small'},
                style: {fontSize: '14px', color: 'red'},
                on: {
                  click: () => {
                    this.downloadFile(params.row);
                  }
                }
              }, '下载')
            ]);
          }
        },

      ],
      infos: [],
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1
      },
      ruleCustom: {
        name: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        content: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }]
      },
      imgBase64: '',
      addButten: true
    }
  },
  watch: {
    "modal1": function (qw, er) {
      if (qw && this.isUpdate) {
        // setTimeout(()=>{
        //     this.$refs.child.setCurrentOrg()
        // },100)
      } else {
        this.form1data = {};
        this.docFile = null;
        this.uploadList = [];
        this.docName = '';
        this.query();
      }
    },
  },
  mounted() {
    this.divHeight = window.innerHeight - 135 + 'px';
    this.tableHeight = window.innerHeight - 305;
    this.categoryId = -1;
    this.queryTree(0);
    this.query();
  },
  methods: {
    handleLoadData(item, callback) {
      this.$http.get(Api.saAuditMaterialsCategory, {params: {parentId: item.id}}).then((res) => {
        let data = res.data
        data.forEach(item => {
          item.loading = false;
          item.children = [];
        })
        console.log(this.treeData);
        callback(data);
      }).catch(e => {
        this.$Message.error('请求失败');
      })

    },
    queryTree(parentId, treeItem) {
      let _this = this;
      this.$http.get(Api.saAuditMaterialsCategory, {params: {parentId: parentId}}).then((res) => {
        if (parentId == 0) {
          let treeData = res.data;
          treeData.forEach(item => {
            item.expand = false;
            item.loading = false;
            item.children = [];
            // this.queryTree(item.id,item)
          })
          _this.treeData = treeData;
        }
      })
    },
    treeDataForEach(treeData, parentId, res) {
      treeData.forEach(i => {
        // i.selected=false
        if (parentId == i.id) {
          i.children = res.data
          // i.selected=true
          i.expand = true
        } else {
          this.treeDataForEach(i.children, parentId, res)
        }
      })
    },
    renderContent(h, {root, node, data}) {
      return h('span', {
        style: {
          display: 'inline-block',
          cursor: 'pointer',
        },
        on: {
          /* click: () => {
               this.isShow = true;
               this.categoryId = data.id;
               this.query(data.id);
           },*/
          click: () => {
            // this.isShow = true;
            // this.showEdit = false;
            this.addButten = false
            if (data.id == '-1' || data.parentId == '-1') {
              this.addButten = true
            }
            this.selectNodeInfo = data;
            this.categoryId = data.id;
            this.formItem = {
              // name: this.selectNodeInfo.title,
              // id: this.selectNodeInfo.id,
              // seq: this.selectNodeInfo.seq
            }
            this.query(data.id);
          },
          contextmenu: (e) => {
            if (data.parentId == -1 || data.parentId == 0) {
              this.showPoint = true;
              this.showPoint1 = true;
              if (data.parentId == -1) {
                this.showPoint2 = true;
              } else {
                this.showPoint2 = false;
              }
            } else {
              this.showPoint1 = false;
              this.showPoint = true;
              this.showPoint2 = true;
            }
            e.preventDefault();
            this.selectNodeInfo = data;
            this.selectNode = node;
            this.selectRoot = root;
            this.$refs.contentMenu.$refs.reference = event.target;
            this.$refs.contentMenu.currentVisible = !this.$refs.contentMenu.currentVisible;
          },
        }
      }, [
        h('span', [
          h('Icon', {
            props: {
              type: 'ios-folder-outline'
            },
            style: {
              marginRight: '8px'
            }
          }),
          h('span', data.title)
        ]),
      ]);
    },
    query() {
      this.loading = true;
      let data = {
        page: this.pagedata.currentPage,
        rows: this.pagedata.pageSize,
        categoryId: this.categoryId
      };
      data = Object.assign(data, JSON.parse(JSON.stringify(this.formInline)));
      this.$http.get(Api.saAuditMaterialsInfo, {
        params: data,
      }).then((res) => {
        this.infos = res.data.data;
        this.pagedata.total = res.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error('请求失败');
      });
    },
    cancel() {
      this.formInline = {};
      this.query();
    },
    add() {
      this.isUpdate = false;
      this.materialsId = this.uuid();
      this.docFile = null
      this.docName = null
      this.uploadImgUrl = Api.uploadPTWFiles + '/' + this.materialsId + '/files/picture';
      this.fileUrl = Api.uploadPTWFiles + '/' + this.materialsId + '/files/doc';
      this.modal1 = true;
    },
    downloadFile(file) {
      this.fileUrl = Api.uploadPTWFiles + '/' + file.id + '/files/doc';
      this.$http.get(this.fileUrl, {
        params: {},
      }).then((res) => {
        if (res.data.result == "success") {
          if (res.data.data.length != 0) {
            // this.docFile = res.data.data[0];
            // this.docName = res.data.data[0].fileName;
            console.log(res.data.data[0].id)
            this.$Modal.confirm({
              title: '文件下载',
              content: '<p>是否确定下载</p>',
              okText: '确认',
              onOk: () => {
                this.$http.get(Api.uploadPTWFiles + '/file/' + res.data.data[0].id, {
                  responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res1) => {
                  console.log(res1)
                  const aLink = document.createElement("a");
                  let blob = new Blob([res1.data], {
                    type: res1.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                  });
                  aLink.href = URL.createObjectURL(blob)
                  aLink.download = res.data.data[0].fileName //标题
                  aLink.click()
                  document.body.appendChild(aLink)
                })
              }
            });
          }
        }
      })


    },
    update(row) {
      this.isUpdate = true;
      this.modal1 = true;
      this.form1data = row;
      this.uploadImgUrl = Api.uploadPTWFiles + '/' + row.id + '/files/picture';
      this.fileUrl = Api.uploadPTWFiles + '/' + row.id + '/files/doc';
      this.$http.get(this.uploadImgUrl, {
        params: {},
      }).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data;
        }
      })
      this.$http.get(this.fileUrl, {
        params: {},
      }).then((res) => {
        if (res.data.result == "success") {
          if (res.data.data.length != 0) {
            this.docFile = res.data.data[0];
            this.docName = res.data.data[0].fileName;
          }
        }
      })
    },
    delete(row) {
      this.$Modal.confirm({
        title: '数据删除',
        content: '<p>确定删除该数据</p>',
        okText: '确认',
        onOk: () => {
          let data = sessionStorage('userId').getObject('userId');
          this.$http.delete(Api.saAuditMaterialsInfo, {params: {id: row.id, updateUserId: data.userId}}).then((res) => {
            this.query();
            this.$Message.success({
              content: '删除成功',
              duration: 4
            });
          }).catch(e => {
            this.$Message.error({
              content: '请求失败',
              duration: 4
            });
          });
        }
      });
    },
    handleUpload(file) {
      let self = this;
      this.imgFile = file;
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (ev) { //文件读取成功完成时触发
        self.imgBase64 = ev.target.result; //获得文件读取成功后的DataURL,也就是base64编码
      }
      return false;
    },
    handleUpload2(file) {
      if (this.docFile != null) {
        debugger;
        this.$http.delete(Api.uploadPTWFiles + '/' + this.form1data.id + '/files/' + this.docFile.id, {params: {}}).then((res) => {
          if (res.data.result == 'success') {
            this.docFile = file;
            this.docName = file.name;
            this.$refs.docUpload.post(this.docFile);
          }
        })
      } else {
        this.docFile = file;
        this.docName = file.name;
        this.$refs.docUpload.post(this.docFile);
      }
      return false;
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    selectTreeItem(name) {
      debugger;
      if (name == 'addPoint') {
        this.isUpdate = false;
        this.showEdit = true;
        this.isShow = true;
        this.formItem.parentId = this.selectNodeInfo.id;
      } else if (name == 'editPoint') {
        this.isUpdate = true;
        this.showEdit = true;
        this.isShow = true;
        this.formItem = {
          id: this.selectNodeInfo.id,
          name: this.selectNodeInfo.title,
          seq: this.selectNodeInfo.seq
        }
      } else if (name == 'deletePoint') {
        this.$Modal.confirm({
          title: '数据删除',
          content: '<p>确定删除该分类</p>',
          okText: '确认',
          onOk: () => {
            let data = sessionStorage('userId').getObject('userId');
            this.$http.delete(Api.saAuditMaterialsCategory, {
              params: {
                id: this.selectNodeInfo.id,
                updateUserId: data.userId
              }
            }).then((res) => {
              const parentKey = this.selectRoot.find(el => el === this.selectNode).parent;
              const parent = this.selectRoot.find(el => el.nodeKey === parentKey).node;
              for (let i = 0; i < parent.children.length; i++) {
                if (parent.children[i].menuId == this.selectNodeInfo.menuId) {
                  console.log(parent.children[i].menuId)
                  console.log(this.selectNodeInfo.menuId)
                  parent.children.splice(i, 1);
                  this.$Message.success('删除成功');
                  this.queryTree(0);
                  this.query();
                  return;
                }
              }
              this.queryTree(0);
              this.query();
              this.$Message.success({
                content: '删除成功',
                duration: 4
              });
            }).catch(e => {
              this.$Message.error({
                content: '请求失败',
                duration: 4
              });
            });

          },
          cancelText: '取消'
        });
      }
    },
    saveInfo() {
      this.$refs['formCustom1'].validate((valid) => {
        if (valid) {
          // this.upload ();
          let data = sessionStorage('userId').getObject('userId');
          if (this.isUpdate) {
            this.form1data.updateUserId = data.userId;
            this.form1data.coverBase64 = this.imgBase64 != '' ? this.imgBase64 : '';
            this.$http.put(Api.saAuditMaterialsInfo, this.form1data).then((res) => {
              this.queryTree(this.form1data.id);
              this.query();
              this.$Message.success({
                content: '保存成功',
                duration: 4
              });
              this.closeModal();
            }).catch(e => {
              this.$Message.error({
                content: '请求失败',
                duration: 4
              });
            });
          } else {
            this.form1data.categoryId = this.categoryId;
            this.form1data.createUserId = data.userId;
            this.form1data.id = this.materialsId;
            this.form1data.coverBase64 = this.imgBase64 != '' ? this.imgBase64 : '';
            this.$http.post(Api.saAuditMaterialsInfo, this.form1data).then((res) => {
              this.queryTree(this.form1data.id);
              this.query();
              this.$Message.success({
                content: '保存成功',
                duration: 4
              });
              this.closeModal();
            }).catch(e => {
              this.$Message.error({
                content: '请求失败',
                duration: 4
              });
            });
          }
        }
      });
    },
    handleRemove(file, type) {
      this.$http.delete(Api.uploadPTWFiles + '/' + this.form1data.id + '/files/' + file.id, {params: {}}).then((res) => {
        if (res.data.result == 'success') {
          if (type == 'picture') {
            this.uploadList.splice(this.uploadList.indexOf(file), 1);
            this.imgFile = null;
          } else if (type == 'doc') {
            this.docName = '';
          }
        }
      })
    },
    upload() { // 上传文件

      if (this.imgFile != null) this.$refs.imgUpload.post(this.imgFile);

      console.log(this.$refs.docUpload);

      if (this.docFile != null) this.$refs.docUpload.post(this.docFile);
    },
    closeModal() {
      this.modal1 = false;
      this.form1data = {};
    },
    save() {
      this.$refs['formCustom'].validate((valid) => {
        if (valid) {
          let data = sessionStorage('userId').getObject('userId');
          if (this.isUpdate) {
            this.formItem.updateUserId = data.userId;
            this.$http.put(Api.saAuditMaterialsCategory, this.formItem).then((res) => {
              this.queryTree(0);
              // this.queryTree(0);
              this.isShow = false;
              this.$Message.success({
                content: '保存成功',
                duration: 4
              });
            }).catch(e => {
              this.$Message.error({
                content: '请求失败',
                duration: 4
              });
            });
          } else {
            this.formItem.id = this.uuid();
            this.formItem.createUserId = data.userId;
            this.$http.post(Api.saAuditMaterialsCategory, this.formItem).then((res) => {
              this.queryTree(0);
              this.isShow = false;
              this.$Message.success({
                content: '保存成功',
                duration: 4
              });
            }).catch(e => {
              this.$Message.error({
                content: '请求失败',
                duration: 4
              });
            });
          }
        }
      });
    },
    uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      let uuid = s.join("");
      return uuid
    }
  }
}
</script>

<style scoped>
@import '../../../index.css';

.upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-right: 4px;
}

.upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.upload-list:hover .upload-list-cover {
  display: block;
}

.upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}

.ivu-row {
  position: relative;
  margin-left: 0;
  margin-right: 0;
  height: auto;
  zoom: 1;
  display: block;
}
</style>
